<template>
  <div>
    <div id="olMap" v-loading="loading"></div>
    <div style="display: none">
      <div id="tag" class="tag"></div>
    </div>
    <div style="padding-top: 20px">
      <el-button @click="handleMap">测试</el-button>
      <el-button @click="showLayer">显示图层</el-button>
      <el-button @click="hideLayer">关闭图层</el-button>
      <el-button @click="addPoint">添加点</el-button>
      <el-button @click="addGeoJson">添加GeoJson</el-button>
      <el-button @click="addGeoJson">切换底图1</el-button>
      <el-button @click="addGeoJson">切换底图2</el-button>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import TileArcGISRest from "ol/source/TileArcGISRest";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { Icon, Style, Text, Fill, Stroke, Circle } from "ol/style";
import { LineString, Point, Polygon } from "ol/geom";
import Overlay from "ol/Overlay";
import { fromLonLat, toLonLat } from "ol/proj";
import GeoJSON from "ol/format/GeoJSON";
import axios from "axios";

export default {
  data() {
    return {
      map: null,
      loading: false,
    };
  },
  mounted() {
    this.init();
    this.mapEvent();
    this.addPoint();
  },
  methods: {
    init() {
      this.loading = true;
      this.map = new Map({
        target: "olMap",
        layers: [
          new TileLayer({
            source: new XYZ({
              url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
              wrapX: true,
            }),
            id: "gaodeditu",
            visible: true,
          }),
        ],
        view: new View({
          center: [106.587866, 29.56688],
          zoom: 15,
          projection: "EPSG:4326",
        }),
      });
      // this.map.on("postrender", (e) => {
      //   console.log('postrender', e);
      // });
      // 地图拖动
      this.map.on("moveend", (e) => {
        console.log("moveend", e);
      });
      // 指针移动
      this.map.on("pointermove", (e) => {
        // console.log('pointermove', e);
        this.map.getTargetElement().style.cursor = this.map.hasFeatureAtPixel(
          e.pixel
        )
          ? "pointer"
          : "";
      });
      // 底图加载完成
      this.map.on("rendercomplete", (e) => {
        this.loading = false;
        console.log("rendercomplete", e);
      });
    },
    mapEvent() {
      this.map.on("singleclick", (e) => {
        console.log("singleClick", e);

        const fea = this.map.forEachFeatureAtPixel(
          e.pixel,
          (feature) => {
            // style.getStroke().setColor("green");
            // statusElement.innerHTML = " 一个要素被选中了!";
            return feature;
          },
          {
            hitTolerance: 20,
          }
        );
        console.log("fea", fea);
        if (fea) {
          let ns = new Style({
            image: new Icon({
              src: require("../../assets/people.png"),
              scale: 0.3,
            }),
          });
          fea.setStyle(ns);
        }
      });

      // this.map.on("pointermove", function (evt) {
      //   console.log("pointermove", evt);

      //   if (evt.dragging) {
      //     return;
      //   }
      //   const pixel = this.map.getEventPixel(evt.originalEvent);
      //   console.log("pixel", pixel);
      // });
    },

    handleMap() {
      console.log("map", this.map.getLayers().getArray());
      console.log("view", this.map.getView());
      // this.map.removeLayer(this.map.getLayers().getArray()[1])
      // let layer = this.map.getLayers().getArray()[1]
      // let fea = layer.getFeatures()
      // console.log('fea',fea);
      // let layer = this.map.getLayers().getArray()
      // layer.forEach(item => {
      //   console.log('item',item);
      //   if(item.values_.id !== 'gaodeditu') {
      //     this.map.removeLayer(item)
      //   }
      // })
    },
    showLayer() {
      let layer = this.map.getLayers().getArray()[0];
      layer.setVisible(true);
    },
    hideLayer() {
      let layer = this.map.getLayers().getArray()[0];
      layer.setVisible(false);
    },
    addPoint() {
      const pos = fromLonLat([106.576495, 29.564519]);
      console.log("pos", pos);

      var tag = new Overlay({
        position: pos,
        positioning: "center-center",
        element: document.getElementById("tag"),
        stopEvent: false,
      });
      this.map.addOverlay(tag);

      const point = new Feature({
        geometry: new Point([106.588467, 29.568653]),
      });
      const style = new Style({
        image: new Icon({
          // 指定锚 x 值的单位。的值'fraction'表示 x 值是图标的一部分。的值'pixels'表示以像素为单位的 x 值。
          anchorXUnits: "fraction",
          // 左下角为原点
          anchorOrigin: "bottom-left",
          anchorYUnits: "fraction",
          anchor: [0.5, 0],
          // scale: 0.8,
          src: require("@/assets/icon_1.png"),
        }),
        zIndex: 2,
      });
      const labelStyle = new Style({
        text: new Text({
          text: "设备总数：24",
          // text:  ['foo', 'bold 10px sans-serif', ' bar', 'italic 10px sans-serif', ' baz', ''],
          font: "14px Microsoft YaHei",
          offsetY: -14,
          offsetX: 33,
          padding: [5, 10, 0, 43],
          textAlign: "left",
          backgroundFill: new Fill({
            color: "rgba(3, 45, 69, 1)",
          }),
          fill: new Fill({
            color: "#fff",
          }),
        }),
        zIndex: 1,
      });
      const otherStyle = new Style({
        image: new Circle({
          radius: 10,
          fill: new Fill({
            color: "#ff0000",
          }),
          stroke: new Stroke({
            color: "#fff",
            width: 2,
          }),
        }),
        text: new Text({
          text: "14",
          font: "12px Times New Roman",
          fill: new Fill({
            color: "#fff",
          }),
        }),
        zIndex: 3,
      });
      point.setStyle([style, labelStyle, otherStyle]);
      point.id = "test666";
      point.name = "测试name";
      console.log("point", point);

      let source = new VectorSource({
        features: [point],
      });
      console.log("source", source);

      // source.addFeatures([point]);
      // source.addFeature(point);
      let layer = new VectorLayer();
      layer.setSource(source);
      this.map.addLayer(layer);
    },
    /**
     * 设置Style
     */
    setStyleOnPersonLocation(feature) {
      const data = feature;
      var imgUrl = require("@/assets/circleLocate.png");

      // 绘制圆角矩形
      let canvas = document.createElement("canvas");
      canvas.width = 80;
      canvas.height = 80;
      var context = canvas.getContext("2d");
      var img = new Image();
      img.src = imgUrl; // 原始图片
      let w = canvas.width;
      let h = canvas.height;
      img.onload = function () {
        context.save();
        // context.arc(x,y,r,sAngle,eAngle,counterclockwise);
        context.arc(40, 40, 20, 0, 2 * Math.PI); // 从画布上裁剪出这个圆形
        context.clip();
        // context.drawImage(img,x,y,width,height);
        context.drawImage(img, 20, 20, 40, 40);
      };

      // 设置style
      return new Style({
        image: new Icon({
          crossOrigin: "anonymous",
          img: canvas,
          imgSize: [w, h],
        }),
        text: new Text({
          text: "666这个是选中的",
          offsetY: -26,
          scale: 0.6,
          font: "12px Microsoft YaHei",
          fill: new Fill({
            color: "#808080",
          }),
          stroke: new Stroke({
            color: "#333",
            width: 1,
          }),
        }),
      });
    },
    addGeoJson() {
      let tileLayer = new TileLayer({
        properties: {
          layerName: "sh_tileLayer",
          desc: "蓝黑底图",
        },
        zIndex: 0,
        visible: true,
        source: new TileArcGISRest({
          url: "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
        }),
      });
      this.map.addLayer(tileLayer);

      let data = [];
      axios({
        url: "/CQ_geojson.json",
        method: "GET",
      }).then((r) => {
        data = r.data;
        console.log("data", data);
        var source = new VectorSource({
          features: new GeoJSON().readFeatures(data),
        });
        var vectorLayer = new VectorLayer({
          source: source,
          style: new Style({
            stroke: new Stroke({
              //线样式
              color: "#42b985",
              width: 2,
            }),
          }),
        });
        this.map.addLayer(vectorLayer);
      });
    },
  },
};
</script>

<style>
#olMap {
  width: 900px;
  height: 600px;
}
.tag {
  width: 30px;
  height: 30px;
  background-color: aquamarine;
  border-radius: 100%;
}
</style>